<?php

/**
 * PayPal_Lib Controller Class (Paypal IPN Class)
 *
 * Paypal controller that provides functionality to the creation for PayPal forms, 
 * submissions, success and cancel requests, as well as IPN responses.
 *
 * The class requires the use of the PayPal_Lib library and config files.
 *
 * @package     CodeIgniter
 * @subpackage  Libraries
 * @category    Commerce
 * @author      Ran Aroussi <ran@aroussi.com>
 * @copyright   Copyright (c) 2006, http://aroussi.com/ci/
 *
 */
class Paypal extends MX_Controller {

    function __construct() {
        parent::__construct();
        $this->load->library('paypal_lib');
        $this->load->model('verify_paypal');
    }

    private $__verification_key = '';

    function auto_form() {

        if (!$this->is_postback())
            redirect(base_url());

        if ($this->cart->total_items() > 0) {


            // cart parameter (multiple item)
            $this->paypal_lib->add_field('upload', '1');
            $this->paypal_lib->add_field('cmd', '_cart');

            $this->paypal_lib->add_field('business', BUSINESS_EMAIL);
            $this->paypal_lib->add_field('return', site_url('checkout-success'));
            $this->paypal_lib->add_field('cancel_return', site_url('checkout-cancel'));
            $this->paypal_lib->add_field('notify_url', site_url('paypal/ipn')); // <-- IPN url

            //$custom = md5(random_string('unique', date('YmdHis')));
            
//            $this->phpsession->save('verification_key', $custom);
            //$this->__verification_key = $custom;
            $hash_verify = '';
            $totalprice_verify = 0;
            $i = 1;
            foreach ($this->cart->contents() as $items) {
                $hash_verify .= $items['id'];
                $this->paypal_lib->add_field('item_number_' . $i, $items['id']);
                $this->paypal_lib->add_field('item_name_' . $i, $items['name']);
                $this->paypal_lib->add_field('amount_' . $i, $items['price']);
                $this->paypal_lib->add_field('quantity_' . $i, $items['qty']);
                $totalprice_verify += $items['qty']*$items['price'];
                $i++;
            }
            if(!$this->phpsession->get('added_verify')){
                $time_verify = time();
                $hash_verify = md5($hash_verify.$time_verify);            
                $this->phpsession->save('added_verify', $hash_verify);
                $this->verify_paypal->add_verify(array('hash'=>$hash_verify,'totalprice'=>$totalprice_verify,'timeverify'=>$time_verify));
            }
            else $hash_verify = $this->phpsession->get('added_verify');
            
            $this->paypal_lib->add_field('custom', $hash_verify); // <-- Verify return
//            $this->paypal_lib->dump();
        }
        //
        $this->paypal_lib->paypal_auto_form();
    }

    function cancel() {
//        modules::run('shopping/empty_cart');
        return $this->load->view('paypal/cancel');
    }

    function success() {
//        This is where you would probably want to thank the user for their order
//        or what have you.  The order information at this point is in POST 
//        variables.  However, you don't want to "process" the order until you
//        get validation from the IPN.  That's where you would have the code to
//        email an admin, update the database with payment status, activate a
//        membership, etc.
//        You could also simply re-direct them to another page, or your own 
//        order status page which presents the user with the status of their
//        order based on a database (which can be modified with the IPN code 
//        below).
        
        modules::run('shopping/empty_cart');
        return $this->load->view('paypal/success');
    }

    function ipn() {
        if ($this->paypal_lib->validate_ipn()) {
        /*if(1){
            $this->paypal_lib->ipn_data = array('mc_gross'=>'24.00','custom'=>'2704b596152e8b251a909ab8edf2d2b5','business'=>'tham212001@yahoo.com'
            ,'payer_status'=>'verified', 'payer_email' => 'tham21_1298569620_per@yahoo.com','num_cart_items'=>1,
            'item_number1'=>2,'item_name1'=>'Hydrangeas','item_number2'=>2,'item_name2'=>'Hydrangeas2','address_name'=>'test','quantity1'
            );*/
        mail('tham212001@yahoo.com','TICKET[TESTS]',print_r($this->paypal_lib->ipn_data,1)); 
        /*$this->paypal_lib->ipn_data= array
(
    'mc_gross' => '15.00',
    'protection_eligibility' => 'Ineligible',
    'address_status' => 'confirmed',
    'item_number1' => '3',
    'tax' => '0.00',
    'item_number2' => '2',
    'payer_id' => 'B65N5AHZCX9HL',
    'address_street' => '1 Main St',
    'payment_date' => '00:33:13 Feb 24, 2012 PST',
    'payment_status' => 'Pending',
    'charset' => 'windows-1252',
    'address_zip' => '95131',
    'mc_shipping' => '0.00',
    'mc_handling' => '0.00',
    'first_name' => 'Test',
    'address_country_code' => 'US',
    'address_name' => 'Test User',
    'notify_version' => '3.4',
    'custom' => '3f646bfc51edbca625abbce3e82e0b6c',
    'payer_status' => 'verified',
    'address_country' => 'United States',
    'num_cart_items' => '2',
    'mc_handling1' => '0.00',
    'mc_handling2' => '0.00',
    'address_city' => 'San Jose',
    'verify_sign' => 'AiPC9BjkCyDFQXbSkoZcgqH3hpacAWmkZUW-JDtgiA8SyCpHJGygfrBP',
    'payer_email' => 'tham21_1298569620_per@yahoo.com',
    'mc_shipping1' => '0.00',
    'mc_shipping2' => '0.00',
    'txn_id' => '2UG529121C3276706',
    'payment_type' => 'instant',
    'last_name' => 'User',
    'address_state' => 'CA',
    'item_name1' => 'NGÃ”I NHÃ€ TRONG HáººM - KHÃ”NG DÃ€NH CHO KHÃN',
    'receiver_email' => 'tham212001@yahoo.com',
    'item_name2' => 'JACK & JILL',
    'quantity1' => '1',
    'quantity2' => '1',
    'pending_reason' => 'unilateral',
    'txn_type' => 'cart',
    'mc_gross_1' => '10.00',
    'mc_currency' => 'CAD',
    'mc_gross_2' => '5.00',
    'residence_country' => 'US',
    'test_ipn' => '1',
    'transaction_subject' => '3f646bfc51edbca625abbce3e82e0b6c',
    'ipn_track_id' => '3aeb632ccc96',
); */

//exit('THU MAIL');
//var_dump(((!empty($this->paypal_lib->ipn_data['business']) && $this->paypal_lib->ipn_data['business'] == BUSINESS_EMAIL) || (!empty($this->paypal_lib->ipn_data['receiver_email']) && $this->paypal_lib->ipn_data['receiver_email'] == BUSINESS_EMAIL)));
        if(!empty($this->paypal_lib->ipn_data['custom']) && $this->paypal_lib->ipn_data['payer_status'] == 'verified' && ((!empty($this->paypal_lib->ipn_data['business']) && $this->paypal_lib->ipn_data['business'] == BUSINESS_EMAIL) || (!empty($this->paypal_lib->ipn_data['receiver_email']) && $this->paypal_lib->ipn_data['receiver_email'] == BUSINESS_EMAIL)) && !empty($this->paypal_lib->ipn_data['mc_gross']) && 
            !empty($this->paypal_lib->ipn_data['num_cart_items']) && count($this->paypal_lib->ipn_data['num_cart_items'])>0 
            ){
                //echo 'VO DAY';
                $get_verificationkey = $this->verify_paypal->get_verify(array('hash'=>$this->paypal_lib->ipn_data['custom'],'totalprice'=>$this->paypal_lib->ipn_data['mc_gross']));
                //var_dump($get_verificationkey);
                if(!empty($get_verificationkey)){
                    $this->load->model('ticket/serial_model');
                    $this->load->model('ticket/ticket_model');
                    $this->load->model('invoice/invoice_model');
                    $this->load->model('invoice/invoice_detail_model');
                    $this->load->model('ticket/ticket_serial_model');
                    $this->load->helper('html2pdf_helper');
                    
                    $pdf_filename = md5(time());
                    $id_invoice = $this->invoice_model->insert_invoice(array(
                        'email'=>$this->paypal_lib->ipn_data['payer_email'],
                        'amount'=>$this->paypal_lib->ipn_data['mc_gross'],
                        'invoice_date'=>date('Y-m-d H:i:s'),
                        'status'=>'1',
                        'pdf_file '=>$pdf_filename
                        )
                    );
                    
                    $num_cart_items = $this->paypal_lib->ipn_data['num_cart_items'];
                    $email_class = array();
                    $email_class['from'] = BUSINESS_EMAIL;
                    //$email_class['attach'] = '';
                    $email_class['to'] = $this->paypal_lib->ipn_data['payer_email'];
                    $email_class['name'] = BUSINESS_NAME;
                    $email_class['subject'] = __('pdf_ticket_title');                    
                    $email_class['message'] = '';
                    $list_tickets_paypal = array();
                    if(!empty($id_invoice)){
                        
                        for ($i = 1; $i <= $num_cart_items; $i++) {
                            
                            //Táº¡o ra chuá»—i ngáº«u nhiÃªn duy nháº¥t
                            $random = md5(random_string('unique', date('YmdHis')));
                            //Insert vÃ o báº£ng serial
                            $serial_id = $this->serial_model->add_serial(array('serial_number' => $random));
                            
                            $ticket_id = $this->paypal_lib->ipn_data['item_number' . $i];//item_number
                            $ticket_name = $this->paypal_lib->ipn_data['item_name' . $i]; 
                            $ticket_quantity = $this->paypal_lib->ipn_data['quantity' . $i];
                            //Insert vÃ o báº£ng ticket_serial
                            //if(!isset($this->ticket_serial_model)) $this->load->model('ticket_serial_model');
                            $this->ticket_serial_model->add_ticket_serial(array('serial_id' => $serial_id, 'ticket_id' => $ticket_id));
                            $one_tk = $this->ticket_model->get_ticket(array('id'=>$ticket_id));
                            
                            //var_dump($one_tk);
                            if(!empty($one_tk[0])) {
                                $one_tk = $one_tk[0];
                                /*Insert data to invoice and invoice_detail*/
                                
                                
                                    $this->invoice_detail_model->insert_invoice_detail(array(
                                        'invoice_id'=>$id_invoice,
                                        'serial_id' =>$serial_id,
                                    ));
                                    $list_tickets_paypal[]= array(                                        
                                        'ticket_name' => $ticket_name,
                                        'ticket_expiry_date' => $one_tk->expiry_date,
                                        'ticket_description' => $one_tk->description,
                                        'ticket_serial_number' => $random
                                    );
                                    /*$pdf_data = array(
                                        'folder' => 'ticket',
                                        'filename' => $random,
                                        'html' => $this->load->view('pdf', $pdf_ticket_view, TRUE)
                                    );
                                    $file_path = './files/' . create_pdf_file_dom($pdf_data);
                                    $email_class['attach'][] = $file_path;
                                    $email_class['message'] .= $this->load->view('pdf', $pdf_ticket_view, TRUE).' <br />';
                                    */
                                    /*//Send email to customer
                                    $email_options = array();
                                    $email_options = array(
                                        'sender_email' => BUSINESS_EMAIL,
                                        'sender_name' => BUSINESS_NAME,
                                        'subject' => __('pdf_ticket_title'),
                                        'message' => $this->load->view('pdf', $pdf_ticket_view, TRUE),
                    //                        'to_email' => $this->paypal_lib->ipn_data['payer_email'],
                                        'to_email' => BUSINESS_EMAIL,
                                        'attach' => $file_path,
                                    );
                                    //var_dump($email_options);
                                    //send_email($email_options);

                                    // Send email to admin
                                    unset($email_options['to_email']);
                                    $email_options['to_email'] = BUSINESS_EMAIL;
                                    //$email_options['to_email'] = 'bqdg11@yahoo.com';
                                    //send_email($email_options);*/
                                }
                        }
                }            //End for item returning
                //$email_class['message'] .= '<br /><br /><br />'.__('send_email_footer');
                //send email
                if(!empty($list_tickets_paypal)){
                    $pdf_ticket_view = array('title' => __('pdf_ticket_title'),
                                        'address_name' => $this->paypal_lib->ipn_data['address_name'],
                                        'payer_email' => $this->paypal_lib->ipn_data['payer_email'],
                                        'ticket_list' => $list_tickets_paypal
                                        );
                    $email_class['message'] .= $this->load->view('pdf', $pdf_ticket_view, TRUE).' <br />';
                    
                    $pdf_data = array(
                        'folder' => 'ticket',
                        'filename' => $pdf_filename,
                        'html' => $email_class['message']
                    );
                    $file_path = './files/' . create_pdf_file_dom($pdf_data);
                    $email_class['message'] .= '<br /><br /><br />'.__('send_email_footer');
                    $this->load->library('email');
                    
                    $this->email->clear();
                    $config_mail['charset'] = $this->config->item('charset');
                    $config_mail['mailtype'] ='html';
                    $config_mail['validate'] =TRUE;
                    $this->email->initialize($config_mail);                    
                    $this->email->mailtype('html');
                    $this->email->from($email_class['from'], $email_class['name']);
                    $this->email->to($email_class['to']);
                    $this->email->subject($email_class['subject']);
                    $this->email->message($email_class['message']);
                    $this->email->attach($file_path);
                    $this->email->send();
                    
                    $this->email->clear();
                    $config_mail['charset'] = $this->config->item('charset');
                    $config_mail['mailtype'] ='html';
                    $config_mail['validate'] =TRUE;
                    $this->email->initialize($config_mail);                    
                    $this->email->mailtype('html');
                    $this->email->from($email_class['to'], $email_class['name']);
                    $this->email->to($email_class['from']);
                    $this->email->subject($email_class['subject']);
                    $this->email->message($email_class['message']);
                    $this->email->attach($file_path);
                    $this->email->send();
                }                
            }
        }
        if($this->phpsession->get('added_verify')) $this->phpsession->clear('added_verify');
        if (!$this->is_postback())
            redirect(base_url());
    }
    }
    
}
